package com.github.shiro.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @program: springboot_shiro
 * @description:
 * @author: ruiyanglee
 * @create: 2020-07-22 10:34
 **/
public class JWTUtil {


    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token,String username) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(Constant.PRIVATE_SALT);
            // 创建token验证器
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .withClaim("username", username)
                    .build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            System.out.println(jwt + ":-token is valid");
            System.out.println("过期时间: " + jwt.getExpiresAt());
            return true;
        } catch (Exception e) {
            System.out.println("The token is invalid{} " + e.getMessage());
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            System.out.println("error：{} " + e.getMessage());
            return null;
        }
    }

    /**
     * 生成签名,5min(分钟)后过期
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(String username) {
        Algorithm algorithm = Algorithm.HMAC256(Constant.PRIVATE_SALT);
        Date date = new Date(System.currentTimeMillis() + Constant.EXPIRE_TIME);
        return JWT.create()
                //发行人
                .withIssuer("auth0")
                .withClaim("username", username)//存放数据
                //过期时间
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 获取token中的时间戳
     *
     * @param token
     * @return
     */
    public static Long getCurrentTime(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("currentTime").asLong();
        } catch (JWTCreationException e) {
            return null;
        }
    }
}
